import { _decorator, Component , Node, Size, UITransform } from 'cc';
import { L } from './L';
const { ccclass, property } = _decorator;

/***
 * 垂直滚动
 */
@ccclass('VerticalRolling')
export class VerticalRolling extends Component {
    array: Array<NodeInfo>;

    @property
    speed: number = 100;

    start() {
        let children = this.node.children;
        L.log(`加载到组件列表数量: ${children.length}`);

        this.array = new Array<NodeInfo>();

        for (let child of children) {
            L.log(`加载到组件列表: ${child.name}`);
            this.array.push(new NodeInfo(child, child.getComponent(UITransform).contentSize.height));
        }
    }

    update(dt: number) {
        if(this.array.length < 1) return;

        for(let idx = 0; idx < this.array.length; idx ++) {
            let nodeInfo = this.array[idx];
            nodeInfo.node.setPosition(nodeInfo.node.position.x, nodeInfo.node.position.y - dt * this.speed, nodeInfo.node.position.z)

            if(nodeInfo.node.position.y < - nodeInfo.height) {
                let pre = null;
                if(idx === 0) {
                    pre = this.array[this.array.length - 1]
                } else if(idx === this.array.length - 1) {
                    pre = this.array[0]
                } else {
                    pre = this.array[idx - 1]
                }

                L.log(`组件已经转移到 ${- nodeInfo.height} 高度, 将粘贴到 pre [${pre.node.name}] 的 [y + self.height] [${pre.node.position.y + nodeInfo.height}]坐标上`)
                nodeInfo.node.setPosition(nodeInfo.node.position.x, pre.node.position.y + nodeInfo.height, nodeInfo.node.position.z)
            }
        }
    }
}

class NodeInfo {
    node: Node;
    height: number;

    constructor(node: Node, height: number) {
        this.node = node;
        this.height = height;
    }
}

